var express = require("express");
var router = express.Router();
//可以像jquer一样操作界面
var cheerio = require("cheerio");
//解决乱码问题:
var charset = require("superagent-charset");
//发起请求
var superagent = require("superagent");
charset(superagent);
let URL = "https://juejin.im/";

function f(res) {
  //设置请求头
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTIONS");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
}
/* GET home page. */
router.get("/", function (req, res, next) {
  res.render("index", {
    title: "express"
  });
});

router.get("/a", function (req, res, next) {
  f(res);
  //网页页面信息是gb2312，所以chaeset应该为.charset('gb2312')
  //一般网页则为utf-8,可以直接使用.charset('utf-8')
  superagent
    .get(URL)
    .end((err, sres) => {
      //页面获取到的数据
      if (err) {
        throw err;
      }
      //用 cheerio 解析页面数据
      var arr = [];
      var $ = cheerio.load(sres.text);
      //下面类似于jquery的操作，前端的小伙伴们肯定很熟悉啦
      // res.send(arr);
      $('div[class=user-popover-box]>a').each((index, element) => {
        if ($(element).text()) {
          console.log($(element).text())
        }
      })
    });
});

module.exports = router;